import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Author：ricardo
 * @Version：1.0
 * @Date：2021/11/5-11:48
 * @Since:jdk1.8
 * @Description:
 */
public class HttpUrlConnectionDemo {
    @Test
    public void httpUrlConnectionTest(){
        InputStream inputStream = null;
        try {
            //1.把请求地址包装成url对象
            URL url = new URL("http://api.tianapi.com/aqi/index?key=63cea1835584c41fbeef939bfde87296&area=武汉");
            //2.根据url获取httpUrlConnection对象
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //3.设置请求方式
            httpURLConnection.setRequestMethod("GET");
            //4.建立连接
            httpURLConnection.connect();
            //5.获取返回的流对象
            inputStream = httpURLConnection.getInputStream();

            byte[] bytes = new byte[1024];
            int length=0;
            StringBuffer stringBuffer=new StringBuffer();
            while ((length=inputStream.read(bytes))!=-1){
                String s = new String(bytes, 0, length);
                stringBuffer.append(s);
            }
            String result = stringBuffer.toString();
            System.out.println(result);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
